<template>
  <div class="comments-container gap-col-16">
    <div v-for="comment in comments" :key="comment.id" class="comment gap-col-8">
      <slot v-bind="{ id: comment.id, comment }"></slot>
      <div v-if="comment.reply_num > 0" class="comments-container gap-col-16">
        <div v-for="reply in comment.replyFetcher.dataList" :key="reply.id" class="comment reply gap-col-8">
          <slot v-bind="{ id: comment.id, comment: reply }"></slot>
        </div>
        <div
          v-if="comment.replyFetcher.dataList.length < comment.reply_num && !comment.replyFetcher.loading"
          class="font-size-14 font-weight-400 line-height-140 text-subtitle-x text-center pointer"
          @click="loadReplyComments(comment.replyFetcher)"
        >
          {{
            $t('message.view') +
            ' ' +
            (comment.reply_num - comment.replyFetcher.dataList.length) +
            ' ' +
            $t('message.messages')
          }}
        </div>
        <div
          v-else-if="comment.replyFetcher.loading"
          class="font-size-14 font-weight-400 line-height-140 text-subtitle-x text-center"
        >
          {{ $t('common.loading') }}
        </div>
      </div>
    </div>
    <div v-if="isLoading" class="loading font-size-14 font-weight-400 line-height-140 text-center">
      {{ $t('common.loading') }}
    </div>
    <div v-if="noMore" class="no-more font-size-14 font-weight-400 line-height-140 text-center">
      {{ $t('common.noMore') }}
    </div>
  </div>
</template>

<script setup>
import { watch } from 'vue'
import { useInfinite } from '@/compositions/request/infinite'
import API from '@/http'

const props = defineProps({
  feedId: { type: Number },
  comments: { type: Array, default: () => [] },
  isLoading: { type: Boolean, default: false },
  noMore: { type: Boolean, default: false },
})

watch(
  () => props.comments,
  (newComments) => {
    newComments.forEach((comment, i) => {
      if (comment.reply_num > 0 && !comment.replyFetcher) {
        comment.replyFetcher = useInfinite({
          request: API.Comment.list,
          params: { id: props.feedId, reply_comment_id: comment.id },
        })
      }
    })
  },
  {
    deep: true,
  },
)

function loadReplyComments(fetcher) {
  if (fetcher.dataList.length === 0) {
    fetcher.init()
  } else {
    fetcher.nextPage()
  }
}
</script>

<style lang="scss" scoped>
.comments-container,
.comment {
  display: flex;
  flex-direction: column;
}

.reply {
  padding-left: 1.5rem;
}
</style>
